/**
 * 
 */
package cn.com.gxetc.assistant.web;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.gxetc.assistant.utils.JwtUtils;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;

/**
 * @author yfm
 *
 */
@Controller
public class HomeController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@GetMapping("/")
	public String index() {
		return "forward:index.html";
	}

	@Autowired
	private WxCpService wxCpService;

	@Autowired
	private JwtUtils jwtUtils;

	@GetMapping("/auth")
	public String auth(@RequestParam(required = true) String code, @RequestParam(required = false) String state,
			HttpServletResponse response) throws Exception {

		String redirectUrl = URLEncoder.encode("http://assistant.gxetc.com.cn/auth", "utf8");
		String url = wxCpService.getOauth2Service().buildAuthorizationUrl(redirectUrl, state);
		if (StringUtils.isEmpty(code)) {
			return "redirect:" + url;
		}
		// 获取userid
		String[] res;
		try {
			res = wxCpService.getOauth2Service().getUserInfo(code);
		} catch (WxErrorException e) {
			logger.error(e.getMessage());
			return "redirect:" + url;
		}
		String userId = res[0];
		if (null == userId) {
			return "redirect:" + url;
		}
		String token=jwtUtils.generateToken(userId);
		Cookie cookie = new Cookie("token",token);  
		cookie.setHttpOnly(true);//防止js操作泄露
        response.addCookie(cookie);  
        
		return "redirect:/index.html";
	}

}
